package cn.edu.tsinghua.cic.ccss.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.forten.core.ro.DtoResultWithPageInfo;
import org.forten.dataio.excel.ExcelUtil;
import org.forten.dataio.excel.exporter.Excel2003Exporter;
import org.forten.dataio.excel.exporter.Excel2007Exporter;
import org.forten.dataio.excel.exporter.ExcelExporter;
import org.forten.utils.collection.CollectionUtil;
import org.forten.utils.system.LogUtil;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.edu.tsinghua.cic.ccss.bo.CadreBo;
import cn.edu.tsinghua.cic.ccss.bo.CourseBo;
import cn.edu.tsinghua.cic.ccss.bo.CoursewareBo;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto4ExportSignIn;
import cn.edu.tsinghua.cic.ccss.dto.CourseDto;
import cn.edu.tsinghua.cic.ccss.dto.CourseDto4Export;
import cn.edu.tsinghua.cic.ccss.dto.CourseDto4Import;
import cn.edu.tsinghua.cic.ccss.dto.CourseDto4Save;
import cn.edu.tsinghua.cic.ccss.dto.CoursewareDto;
import cn.edu.tsinghua.cic.ccss.entity.Courseware;
import cn.edu.tsinghua.cic.ccss.qo.CourseQo;

/**课程信息Controller
 * @author cj
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("course")
@SessionAttributes("courseQo")
public class CourseAction extends SuperAction {
	private static Logger log = Logger.getLogger(CourseAction.class);
	private static final String CADRE_DELETE_MSG = "课程信息删除:%s";

	@Resource(name = "courseQo")
	private CourseQo courseQo;
	@Resource(name = "courseBo")
	private CourseBo courseBo;
	@Resource(name = "cadreBo")
	private CadreBo cadreBo;
	@Resource(name = "coursewareBo")
	private CoursewareBo coursewareBo;
	private String message = null;

	@RequestMapping("gotoCourseList")
	public String gotoCourseList(Model model) {
		model.addAttribute("courseQo", courseQo);
		return "forward:showCourseList.jspx";
	}

	@RequestMapping("showCourseList")
	public String showCourseList(Model model,
			@RequestParam(defaultValue = "1") int pageNo,
			@ModelAttribute("courseQo") CourseQo courseQo) {
		DtoResultWithPageInfo<CourseDto> dto = courseBo.queryCourseDtoPage(
				courseQo, pageNo,"teachTime",false);
		model.addAttribute("courseQo", courseQo);
		model.addAttribute("page", dto.getPageInfo());
		model.addAttribute("dto", dto.getResults());
		return "course/kkxxList";
	}

	@RequestMapping("export2003")
	public void export2003(HttpServletResponse response,
			HttpServletRequest request,
			@ModelAttribute("courseQo") CourseQo courseQo) {
		List<CourseDto4Export> result = courseBo.export(courseQo);
		ExcelExporter export = new Excel2003Exporter();
		Workbook wb = export.export(result);
		if (wb == null) {
			RequestDispatcher view = request
					.getRequestDispatcher("../WEB-INF/pages/error-msg.jsp");
			try {
				List<String> errMsg = new ArrayList<String>();
				errMsg.add("导出数据结果集为空");
				request.setAttribute("errMsg", errMsg);
				request.setAttribute("url", "gotoCourseList.jspx");
				view.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			ExcelUtil.downloadFile(response, wb,
					"CourseInfo" + export.getPostfix());
		}
	}

	@RequestMapping("export2003SignIn")
	public void export2003SignIn(HttpServletResponse response,
			HttpServletRequest request, @RequestParam Long courseId) {
		List<CadreDto4ExportSignIn> result = cadreBo
				.exportSignInTable(courseId);
		ExcelExporter export = new Excel2003Exporter();
		Workbook wb = export.export(result);
		if (wb == null) {
			RequestDispatcher view = request
					.getRequestDispatcher("../WEB-INF/pages/error-msg.jsp");
			try {
				List<String> errMsg = new ArrayList<String>();
				errMsg.add("导出数据结果集为空");
				request.setAttribute("errMsg", errMsg);
				request.setAttribute("url", "gotoCourseList.jspx");
				view.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			ExcelUtil.downloadFile(response, wb,
					"SignInTable" + export.getPostfix());
		}
	}

	@RequestMapping("export2007")
	public void export2007(HttpServletResponse response,
			HttpServletRequest request,
			@ModelAttribute("courseQo") CourseQo courseQo) {
		List<CourseDto4Export> result = courseBo.export(courseQo);
		ExcelExporter export = new Excel2007Exporter();
		Workbook wb = export.export(result);
		if (wb == null) {
			RequestDispatcher view = request
					.getRequestDispatcher("../WEB-INF/pages/error-msg.jsp");
			try {
				List<String> errMsg = new ArrayList<String>();
				errMsg.add("导出数据结果集为空");
				request.setAttribute("errMsg", errMsg);
				request.setAttribute("url", "gotoCourseList.jspx");
				view.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			ExcelUtil.downloadFile(response, wb,
					"CourseInfo" + export.getPostfix());
		}
	}

	@RequestMapping("export2007SignIn")
	public void export2007SignIn(HttpServletResponse response,
			HttpServletRequest request, @RequestParam Long courseId) {
		List<CadreDto4ExportSignIn> result = cadreBo
				.exportSignInTable(courseId);
		ExcelExporter export = new Excel2007Exporter();
		Workbook wb = export.export(result);
		if (wb == null) {
			RequestDispatcher view = request
					.getRequestDispatcher("../WEB-INF/pages/error-msg.jsp");
			try {
				List<String> errMsg = new ArrayList<String>();
				errMsg.add("导出数据结果集为空");
				request.setAttribute("errMsg", errMsg);
				request.setAttribute("url", "gotoCourseList.jspx");
				view.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			ExcelUtil.downloadFile(response, wb,
					"SignInTable" + export.getPostfix());
		}
	}

	@RequestMapping("gotoCourseAdd")
	public String gotoCourseAdd(Model model) {
		model.addAttribute("addDto", new CourseDto4Save());
		return "course/addkkxx";
	}

	@RequestMapping("addCourse")
	public String addCourse(
			@ModelAttribute("addDto") CourseDto4Save courseDto4Save, Model model) {
		courseBo.doSave(courseDto4Save);
		message = "新增课程成功！";
		model.addAttribute("message", message);
		return "forward:showCourseList.jspx";
	}

	@RequestMapping("gotoCourseEdit")
	public String gotoCourseEdit(Model model, Long id,@RequestParam(defaultValue = "")String flag) {
		
		CourseDto courseDto = courseBo.loadCourseDto(id);
		model.addAttribute("flag", flag);
		model.addAttribute("editDto", courseDto);
		return "course/editkkxx";
	}

	@RequestMapping("editCourse")
	public String editCourse(Model model,
			@RequestParam(defaultValue = "") String flag,
			@ModelAttribute("editDto") CourseDto courseDto,SessionStatus status) {
		courseBo.doUpdate(courseDto);
		message = "编辑信息操作成功";
		model.addAttribute("message", message);
		//TODO qo米有被清空
		courseQo.clean();
		status.setComplete();
		if (flag.isEmpty()) {
			model.addAttribute("courseQo", courseQo);
			return "forward:gotoCourseList.jspx";
		} else {
			return "redirect:/selectcourse/gotoCourseSelectByAdminList.jspx";
		}
	}

	@RequestMapping("deleteCourse")
	public String deleteCourse(Model model,
			@RequestParam(defaultValue = "") Long id) {
		LogUtil.debug(log, CADRE_DELETE_MSG);
		CourseDto courseDto = courseBo.loadCourseDto(id);
		if (courseDto != null) {
			courseBo.doDelete(id);
			message = "删除操作成功！";
		} else {
			message = "删除失败，非法ID";
		}
		courseQo.clean();
		return "redirect:gotoCourseList.jspx";
	}

	@RequestMapping("gotoUploadCourseData")
	public String gotoUploadCourseData() {
		return "course/upload";
	}

	@RequestMapping("uploadData")
	public String uploadData(Model model, HttpServletRequest request) {
		List<CourseDto4Import> list = null;
		try {
			list = ExcelUtil.uploadFile(request, CourseDto4Import.class, 1);
		} catch (Exception e) {
			List<String> msg = new ArrayList<String>();
			msg.add("导入文件格式有误：" + e.getMessage());
			model.addAttribute("errMsg", msg);
			model.addAttribute("url", "../cadre/gotoUploadCadreData.jspx");
			return "error-msg";
		}
		List<String> errMsg = courseBo.doBatchImport(list);
		if (!CollectionUtil.isEmpty(errMsg)) {
			model.addAttribute("errMsg", errMsg);
			model.addAttribute("url", "../course/gotoUploadCourseData.jspx");
			return "error-msg";
		}
		return "redirect:gotoCourseList.jspx";
	}

	//TODO 新增功能，上传课件
	@RequestMapping("gotoUploadCourseware")
	public String gotoUploadCourseware(Model model,
			@RequestParam(defaultValue = "") Long courseId){
		/*List<CoursewareDto> coursewareDtos = coursewareBo.findCoursewareByCourseId(courseId);*/
		CourseDto courseDto = courseBo.loadCourseDto(courseId);
		/*model.addAttribute("coursewareDtos", coursewareDtos);*/
		model.addAttribute("courseDto", courseDto);
		model.addAttribute("courseId", courseId);
		return "course/uploadkj2";
	}
	
	//TODO 新增功能，上传课件
/*	@RequestMapping("showCourseware")
	public void showCourseware(@RequestParam(defaultValue = "") Long id,
			HttpServletRequest request, HttpServletResponse response){
		
	}*/
	
	//TODO 新增功能，上传课件
	@RequestMapping("uploadCourseware")
	public void uploadCourseware(Model model,
			HttpServletRequest request, HttpServletResponse response,
			/*@ModelAttribute("coursewareDto")CoursewareDto coursewareDto,*/
			@RequestParam(defaultValue = "") Long courseId) throws Exception{
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multipartRequest.getFileNames();//获取文件名s
		if(iterator.hasNext()){
			MultipartFile multipartFile = multipartRequest.getFile(iterator.next());
			if(multipartFile != null){
				boolean flag = coursewareBo.checkFileType(multipartFile.getOriginalFilename());
				if(flag == false){
					message = "错误的文件格式！";
					/*model.addAttribute("message", message);
					return "forward:gotoUploadCourseware.jspx";*/
					throw new Exception(message);
				}
				Courseware courseware = new Courseware();
				byte[] fj = multipartFile.getBytes();
				courseware.setCourseware(fj);
				courseware.setWareName(multipartFile.getOriginalFilename());//获取文件名
				courseware.setCourseId(courseId);
				//TODO 添加课件上传操作人信息和操作时间
//				courseware.set
				coursewareBo.doSaveCourseware(courseware);
			} else {
				throw new Exception("上传失败：文件为空");
			}
		}
		/*message = "添加成功！";
		model.addAttribute("message", message);
		return "forward:gotoUploadCourseware.jspx";*/
	}
	
	@RequestMapping("gotoCheckCourseware")
	public String gotoCheckCourseware(Model model,
			@RequestParam(defaultValue = "") Long courseId){
		List<CoursewareDto> coursewareDtos = coursewareBo.findCoursewareByCourseId(courseId);
		model.addAttribute("coursewareDtos", coursewareDtos);
		model.addAttribute("courseId", courseId);
		return "course/kj";
	}
	
	@RequestMapping("deleteCourseware")
	public String deleteCourseware(Model model,
			@RequestParam(defaultValue = "") Long id,@RequestParam(defaultValue = "") Long courseId){
		coursewareBo.doDeleteCourseware(id);
		message = "删除成功！";
		model.addAttribute("message", message);
		model.addAttribute("courseId", courseId);
		return "forward:gotoCheckCourseware.jspx";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
	}
}
